#!/bin/bash
#
# Refers to https://gitee.com/api/v5/swagger
#

if [ "$__GITEE_SH__" ]; then
    return
else
    export __GITEE_SH__="gitee.sh"
fi

# notes:
#   The following variables need to be defined by the user
export gitee_owner=""
export gitee_id=""
export access_token=""

readonly GITEE_HEADER='Content-Type: application/json;charset=UTF-8'
readonly GITEE_URL_PREFIX="https://gitee.com/api/v5/repos"

# fork_repo(repo)
#   Fork the specified repo
# Example:
#   fork_repo fancytool
fork_repo() {
    curl -X POST --header $GITEE_HEADER "$GITEE_URL_PREFIX/$gitee_owner/$1/forks" \
        -d "{\"access_token\":\"$access_token\"}" &>/dev/null
}

# create_pr(repo, title)
#   Create Pull Request
# Example:
#   create_pr fancytool "update scripts"
create_pr() {
    curl -X POST --header $GITEE_HEADER "$GITEE_URL_PREFIX/$gitee_owner/$1/pulls" \
        -d "{\"access_token\":\"$access_token\",\"title\":\"$2\",\"head\":\"$gitee_id:master\",\"base\":\"master\"}" &>/dev/null
}

# get_pr_comments(repo, number)
#   Get all comments of a Pull Request
# Returns:
#   the http response body string
# Example:
#   result=$(get_pr_comments fancytool 1)
get_pr_comments() {
    local result=$(curl -s -X GET --header $GITEE_HEADER "$GITEE_URL_PREFIX/$gitee_owner/$1/pulls/$2/comments" \
        -d "{\"access_token\":\"$access_token\",\"page\":\"1\",\"per_page\":\"20\"}")
    echo "$result"
}

# comment_pr(repo, number, comments)
#   Submit Pull Request comments
# Example
#   comment_pr fancytool 1 "OK"
comment_pr() {
    curl -X POST --header $GITEE_HEADER "$GITEE_URL_PREFIX/$gitee_owner/$1/pulls/$2/comments" \
        -d "{\"access_token\":\"$access_token\",\"body\":\"$3\"}" &>/dev/null
}

# check_pr_merge(repo, number)
#   Determine whether the Pull Request has been merged
# Returns:
#       1 - megerd
#       0 - opened
# Example:
#   result=$(check_pr_merge fancytool 1)
check_pr_merge() {
    local result=$(curl -s -X GET -w '%{http_code}' --header $GITEE_HEADER "$GITEE_URL_PREFIX/$gitee_owner/$1/pulls/$2/merge" \
        -d "{\"access_token\":\"$access_token\"}" | grep -o "200")
    if [ "$result" = "200" ]; then
        return 1
    else
        return 0
    fi
}


